const { makeInvoker } = require('awilix-express')
const { Router } = require('express')
const { responseHelper } = require('../helper')

const api = makeInvoker(
  ({
    createUser,
    getUserPage,
    disableUser,
    updateUser,
    getUserDetail,
    removeUser,
    enableUser,
    resetPassword,
    setSuperAdmin,
  }) => {
    return {
      createUser: responseHelper(async (req, res) => {
        return await createUser.execute(req.body, req.user)
      }),
      getUserPage: responseHelper(async (req, res) => {
        return await getUserPage.execute(req.query)
      }),
      getUserDetail: responseHelper(async (req, res) => {
        return await getUserDetail.execute(req.params.id)
      }),
      disableUser: responseHelper(async (req, res) => {
        return await disableUser.execute(req.params.id)
      }),
      enableUser: responseHelper(async (req, res) => {
        return await enableUser.execute(req.params.id)
      }),
      removeUser: responseHelper(async (req, res) => {
        return await removeUser.execute(req.params.id)
      }),
      updateUser: responseHelper(async (req, res) => {
        return await updateUser.execute({
          id: req.params.id,
          ...req.body,
        })
      }),
      resetPassword: responseHelper(async (req, res) => {
        return await resetPassword.execute(req.params.id)
      }),
      // 赋予超管
      setSuperAdmin: responseHelper(async (req, res) => {
        return await setSuperAdmin.execute(req.params.id, true)
      }),
      // 剥夺超管
      recycleSuperAdmin: responseHelper(async (req, res) => {
        return await setSuperAdmin.execute(req.params.id, false)
      }),
    }
  }
)

module.exports = ({ all }) => {
  const router = Router()
  router
    .post('/', all, api('createUser'))
    .post('/:id/disable', all, api('disableUser'))
    .post('/:id/enable', all, api('enableUser'))
    .post('/:id/resetPassword', all, api('resetPassword'))
    .post('/:id/setSuperAdmin', all, api('setSuperAdmin'))
    .post('/:id/recycleSuperAdmin', all, api('recycleSuperAdmin'))
    .put('/:id', all, api('updateUser'))
    .get('/', all, api('getUserPage'))
    .get('/:id', all, api('getUserDetail'))
    .delete('/:id', all, api('removeUser'))
  return router
}
